<template>
  <div class="login-page">
    <!-- 页面标题 -->
    <div class="page-title">益起行</div>

    <!-- 表单区域 -->
    <van-form ref="form" :model="formData" class="form-container">
      <!-- 登录表单 -->
      <div v-if="!showResetPassword && !showRegister">
        <van-field
          v-model="formData.username"
          label="账号"
          placeholder="请输入账号"
          clearable
        />
        <van-field
          v-model="formData.password"
          label="密码"
          type="password"
          placeholder="请输入密码"
          clearable
        />
        <van-button class="login-button" type="primary" @click="login"
          >登录</van-button
        >

        <div class="links-container">
          <a href="javascript:void(0);" @click="showForgetPassword">忘记密码</a>
          |
          <a href="javascript:void(0);" @click="showRegisterForm">注册账号</a>
        </div>
      </div>

      <!-- 重置密码表单 -->
      <div v-else-if="showResetPassword" class="reset-password-container">
        <van-field
          v-model="formData.username"
          label="账号"
          placeholder="请输入账号"
          clearable
        />
        <van-field
          v-model="formData.email"
          label="邮箱"
          placeholder="请输入邮箱"
          clearable
        />

        <div class="verification-container">
          <van-field
            v-model="formData.code"
            label="验证码"
            placeholder="请输入验证码"
            clearable
          />
          <van-button
            class="send-verification-button"
            @click="sendVerificationCode"
            >发送验证码</van-button
          >
        </div>

        <van-field
          v-model="formData.newPassword"
          label="新密码"
          type="password"
          placeholder="请输入新密码"
          clearable
        />
        <van-field
          v-model="formData.confirmNewPassword"
          label="确认新密码"
          type="password"
          placeholder="请确认新密码"
          clearable
        />

        <van-button
          class="reset-password-button"
          type="primary"
          @click="resetPassword"
          >重置密码</van-button
        >
        <div class="links-container">
          <span class="back-to-login" @click="showLogin">返回登录</span>
        </div>
      </div>

      <!-- 注册表单 -->
      <div v-else-if="showRegister" class="register-container">
        <van-field
          v-model="formData.username"
          label="账号"
          placeholder="请输入账号"
          clearable
        />
        <van-field
          v-model="formData.password"
          label="密码"
          type="password"
          placeholder="请输入密码"
          clearable
        />
        <van-field
          v-model="formData.name"
          label="姓名"
          placeholder="请输入姓名"
          clearable
        />

        <!-- 性别选择框 -->
        <div class="select-container">
          <van-field
            label="性别"
            readonly
            clickable
            v-model="formData.sex"
            placeholder="请选择性别"
            @click="showSexPicker = true"
          />
          <van-popup v-model="showSexPicker" round position="bottom">
            <van-picker
              show-toolbar
              :columns="genderOptions"
              @confirm="
                (value) => {
                  formData.sex = value;
                  showSexPicker = false;
                }
              "
              @cancel="
                () => {
                  showSexPicker = false;
                }
              "
            />
          </van-popup>
        </div>
        <!-- 入学年份选择框 -->
        <div class="select-container">
          <van-field
            label="入学年份"
            readonly
            clickable
            v-model="formData.enrollmentYear"
            placeholder="请选择入学年份"
            @click="showYearPicker = true"
          />
          <van-popup v-model="showYearPicker" round position="bottom">
            <van-picker
              show-toolbar
              :columns="yearRange"
              @confirm="
                (value) => {
                  formData.enrollmentYear = value;
                  showYearPicker = false;
                }
              "
              @cancel="
                () => {
                  showYearPicker = false;
                }
              "
            />
          </van-popup>
        </div>

        <van-field
          v-model="formData.phone"
          label="电话"
          placeholder="请输入电话"
          clearable
        />
        <van-field
          v-model="formData.email"
          label="邮箱"
          placeholder="请输入邮箱"
          clearable
        />
        <van-field
          v-model="formData.address"
          label="地址"
          placeholder="请输入地址"
          clearable
        />
        <van-field
          v-model="formData.studentId"
          label="学号"
          placeholder="请输入学号"
          clearable
        />

        <van-field
          v-model="formData.faculty"
          label="学院"
          placeholder="请输入学院"
          clearable
        />
        <van-button class="register-button" type="primary" @click="register"
          >注册</van-button
        >
        <div class="links-container">
          <span class="back-to-login" @click="showLogin">返回登录</span>
        </div>
      </div>
    </van-form>
  </div>
</template>
  
  <script>
import userApi from "@/api/user.js";
import { Picker, Field, Button, Form, Popup } from "vant";

export default {
  components: {
    "van-picker": Picker,
    "van-field": Field,
    "van-button": Button,
    "van-form": Form,
    "van-popup": Popup,
  },
  data() {
    return {
      formData: {
        username: "",
        password: "",
        name: "",
        sex: "男",
        phone: "",
        email: "",
        address: "",
        studentId: "",
        enrollmentYear: "",
        faculty: "",
        code: "",
        newPassword: "",
        confirmNewPassword: "",
      },
      showSexPicker: false,
      showYearPicker: false,
      showResetPassword: false,
      showRegister: false,
      yearRange: this.generateYearRange(
        new Date().getFullYear() - 4,
        new Date().getFullYear() + 2
      ),
      genderOptions: ["男", "女"],
    };
  },
  methods: {
    clearFormData() {
      for (const key in this.formData) {
        if (this.formData.hasOwnProperty(key)) {
          this.formData[key] = "";
        }
      }
    },
    generateYearRange(start, end) {
      let years = [];
      for (let year = start; year <= end; year++) {
        years.push(year.toString());
      }
      return years;
    },
    showLogin() {
      this.clearFormData();
      this.showResetPassword = false;
      this.showRegister = false;
    },
    showForgetPassword() {
      this.clearFormData();
      this.showResetPassword = true;
      this.showRegister = false;
    },
    showRegisterForm() {
      this.clearFormData();
      this.showResetPassword = false;
      this.showRegister = true;
    },
    login() {
      if (!this.formData.username || !this.formData.password) {
        this.$toast.fail("账号和密码不能为空");
        return;
      }
      const data = {
        username: this.formData.username,
        password: this.formData.password,
      };
      userApi
        .login(data)
        .then((res) => {
          const token = res;
          console.log(token);
          localStorage.setItem("token", token);
          this.$toast.success("登录成功");
          userApi.getUserRole().then((res) => {
            if (res === "USER") {
              this.$router.push("user/activity");
            } else {
              this.$router.push("organizer/activity");
            }
          });
        })
        .catch((err) => {
          console.log(err);
          this.$toast.fail(err.message || "登录失败");
        });
    },
    sendVerificationCode() {
      if (!this.formData.email) {
        this.$toast.fail("请输入邮箱地址");
        return;
      }
      const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
      if (!emailPattern.test(this.formData.email)) {
        this.$toast.fail("请输入有效的邮箱地址");
        return;
      }

      userApi.sendCode(this.formData.email);
      this.$toast.success("验证码已发送");
    },
    resetPassword() {
      if (
        !this.formData.username ||
        !this.formData.email ||
        !this.formData.code ||
        !this.formData.newPassword ||
        !this.formData.confirmNewPassword
      ) {
        this.$toast.fail("请填写所有必填项");
        return;
      }
      if (this.formData.newPassword !== this.formData.confirmNewPassword) {
        this.$toast.fail("两次密码输入不一致");
        return;
      }
      userApi.resetPassword(this.formData);
      this.$toast.success("密码重置成功");
      this.showLogin();
    },
    validateFormData() {
    const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    const phonePattern = /^1[3-9]\d{9}$/;

    if (!this.formData.username) {
      this.$toast.fail("账号不能为空");
      return false;
    }
    if (!this.formData.password || this.formData.password.length < 6 ) {
      this.$toast.fail("密码必须至少6位");
      return false;
    }
    if (!this.formData.name) {
      this.$toast.fail("姓名不能为空");
      return false;
    }
    if (!["男", "女"].includes(this.formData.sex)) {
      this.$toast.fail("请选择有效的性别");
      return false;
    }
    if (!this.formData.phone || !phonePattern.test(this.formData.phone)) {
      this.$toast.fail("请输入有效的11位手机号");
      return false;
    }
    if (!this.formData.email || !emailPattern.test(this.formData.email)) {
      this.$toast.fail("请输入有效的邮箱地址");
      return false;
    }
    if (!this.formData.address) {
      this.$toast.fail("地址不能为空");
      return false;
    }
    if (!this.formData.studentId || isNaN(this.formData.studentId)) {
      this.$toast.fail("学号必须为数字");
      return false;
    }
    if (!this.formData.enrollmentYear || !this.yearRange.includes(this.formData.enrollmentYear)) {
      this.$toast.fail("请选择有效的入学年份");
      return false;
    }
    if (!this.formData.faculty) {
      this.$toast.fail("学院不能为空");
      return false;
    }
    return true;
  },
    register() {
      if (!this.validateFormData()) {
        return;
    }
      userApi.createUser(this.formData);
      this.$toast.success("注册成功");
      this.showLogin();
    },
  },
};
</script>
  
<style scoped>
/* 整个页面布局 */
.login-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding-top: 15vh; /* 顶部间距基于屏幕高度 */
  min-height: 100vh;
  background-color: #f8f8f8;
}

/* 页面标题 */
.page-title {
  font-size: 6vh; /* 标题字体基于屏幕高度 */
  font-weight: bold;
  color: #3b82f6;
  margin-bottom: 5vh; /* 底部间距 */
}

/* 输入框和按钮 */
.van-field {
  width: 100%;
  margin-bottom: 3vh; /* 每个输入框的底部间距 */
}

/* 按钮样式 */
.register-button,
.login-button,
.reset-password-button {
  width: 100%;
  padding: 2.5vh; /* 按钮的内边距 */
  font-size: 2.5vh; /* 按钮文字大小 */
  color: #fff;
  background-color: #3b82f6;
  border: none;
  border-radius: 2vh; /* 按钮圆角 */
  margin-top: 2vh;
  margin-bottom: 5vh;
}

.reset-password-container {
  padding: 1vh; /* 向上缩 1vh */
}

/* 忘记密码和注册链接 */
.links-container {
  font-size: 2.5vh; /* 链接文字大小 */
  display: flex;
  justify-content: center;
}

.links-container a {
  color: #3b82f6;
  margin: 0 2vw; /* 水平方向间距 */
}

/* 验证码输入和按钮 */
.verification-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.verification-input {
  flex-grow: 1;
  margin-right: 2vw;
}

.send-verification-button {
  width: 30%; /* 按钮宽度占容器的百分比 */
  padding: 1.5vh;
  background-color: #3b82f6;
  margin-top: -3vh;
  color: #fff;
  font-size: 2.2vh;
  border-radius: 1vh;
}

/* 性别和入学年份选择框 */
.select-container {
  display: flex;
  align-items: center;
}

.select-label {
  font-size: 2.2vh; /* 标签文字大小 */
  margin-right: 2vw;
}

.select-input {
  width: 100%;
  height: 5vh; /* 输入框高度 */
  padding: 1vh;
  font-size: 2.2vh;
  border-radius: 1vh;
}

/* 弹出框样式 */
.van-popup {
  z-index: 20;
  overflow: hidden;
}

.van-popup .van-picker {
  height: 30vh; /* 控制选择器高度 */
  padding: 0;
  overflow-y: scroll;
}
</style>

  
  